<template>
    <div class="app-container">
        <div class="search-container">
            <el-row :gutter="20">
                <el-col :span="5">
                    <el-input
                        v-model="searchParams.studentName"
                        placeholder="请输入姓名"
                        clearable
                        prefix-icon="el-icon-user"
                    />
                </el-col>
                <el-col :span="5">
                    <el-input
                        v-model="searchParams.dorm"
                        placeholder="请输入宿舍号"
                        clearable
                        prefix-icon="el-icon-office-building"
                    />
                </el-col>
                <el-col :span="5">
                    <el-input
                        v-model="searchParams.bussinesskey"
                        placeholder="请输入业务号"
                        clearable
                        prefix-icon="el-icon-document"
                    />
                </el-col>
                <el-col :span="4">
                    <el-button-group>
                        <el-button type="primary" @click="search">
                            <i class="el-icon-search"></i> 搜索
                        </el-button>
                        <el-button type="info" @click="reset">
                            <i class="el-icon-refresh"></i> 重置
                        </el-button>
                    </el-button-group>
                </el-col>
            </el-row>
        </div>

        <div class="table-container">
            <el-table
                v-loading="loading"
                :data="responseData.rows || []"
                border
                stripe
                highlight-current-row
                style="width: 100%">
                <el-table-column prop="businessKey" label="业务号" min-width="80" align="center" />
                <el-table-column label="当前节点" min-width="120" align="center">
                    <template slot-scope="{row}">
                        <div class="status-tag" :class="getNodeStatusClass(row)">
                            <i :class="getNodeIcon(row)"></i>
                            <span>{{ getNodeText(row) }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="当前处理人" min-width="100" align="center">
                    <template slot-scope="{row}">
                        <div class="handler-tag" :class="{'ended': row.ended && row.endTime}">
                            <i class="el-icon-user"></i>
                            <span>{{ row.ended && row.endTime ? '—' : row.assignee }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="流程状态" width="100" align="center">
                    <template slot-scope="{row}">
                        <el-tag :type="row.ended ? 'success' : 'warning'" effect="plain">
                            <i :class="row.ended ? 'el-icon-check' : 'el-icon-loading'"></i>
                            {{ row.ended ? '已结束' : '进行中' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="时间信息" min-width="280" align="center">
                    <template slot-scope="{row}">
                        <div class="time-info">
                            <el-tooltip effect="dark" placement="top">
                                <div slot="content">
                                    <p>开始时间: {{ row.startTime }}</p>
                                    <p v-if="row.endTime">结束时间: {{ row.endTime }}</p>
                                </div>
                                <div class="time-display">
                                    <i class="el-icon-time"></i>
                                    {{ row.startTime }}
                                    <template v-if="row.endTime">
                                        <i class="el-icon-arrow-right"></i>
                                        {{ row.endTime }}
                                    </template>
                                </div>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="宿舍信息" min-width="120" align="center">
                    <template slot-scope="{row}">
                        <el-tag type="info" effect="plain">
                            {{ row.apartment }}栋{{ row.dorm }}室
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="发起人" min-width="100" align="center">
                    <template slot-scope="{row}">
                        <el-tag type="primary" effect="plain" size="medium">
                            <i class="el-icon-user"></i>
                            {{ row.startUserId }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="班级" width="240" align="center">
                    <template slot-scope="{row}">
                        <el-tooltip class="item" effect="dark" placement="top">
                            <template #content>
                                <span>{{ row.department || '未设置' }}</span>
                            </template>
                            <el-tag type="info" effect="light" size="small" class="class-tag">
                                <i class="el-icon-school" style="font-size: 14px;"></i>
                                <span class="ellipsis-text" style="max-width: 160px;">  <!-- 配合宽度调整文字溢出宽度 -->
                                    {{ row.department || '未设置' }}
                                </span>
                            </el-tag>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right" align="center">
                    <template slot-scope="{row}">
                        <el-button-group>
                            <el-button
                                size="small"
                                type="primary"
                                plain
                                @click="showHistory(row)"
                                icon="el-icon-view"
                                class="mini-btn">
                                历史
                            </el-button>
                            <el-button
                                v-if="!row.suspended"
                                size="small"
                                type="success"
                                plain
                                @click="showVariable(row)"
                                icon="el-icon-document"
                                class="mini-btn">
                                变量
                            </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="searchParams.pageNum"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="searchParams.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="responseData.total || 0">
                </el-pagination>
            </div>
        </div>

        <el-dialog
            title="执行记录"
            :visible.sync="showHistoryDialog"
        >
            <el-table :data="historyList" height="500">
                <el-table-column
                    prop="taskName"
                    label="活动名称">
                </el-table-column>
                <el-table-column
                     prop="type"
                     label="活动类型">
                </el-table-column>
                <el-table-column
                    prop="assignee"
                    label="办理人">
                </el-table-column>
                <el-table-column
                    prop="comment"
                    label="审批意见">
                </el-table-column>
                <el-table-column
                    prop="startTime"
                    label="开始时间">
                </el-table-column>
                <el-table-column
                    prop="endTime"
                    label="结束时间">
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showHistoryDialog = false">取 消</el-button>
                <el-button type="primary" @click="showHistoryDialog = false">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :visible.sync="showVariableDialog"
        >
            <el-table :data="variablesList" height="500">
                <el-table-column
                    prop="variableName"
                    label="变量名">
                </el-table-column>
                <el-table-column
                    prop="variableTypeName"
                    label="变量类型">
                </el-table-column>
                <el-table-column
                    prop="value"
                    label="变量值">
                </el-table-column>
                <el-table-column
                    prop="createTime"
                    label="创建时间">
                </el-table-column>
                <el-table-column
                    prop="lastUpdatedTime"
                    label="最后修改时间">
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showVariableDialog = false">取 消</el-button>
                <el-button type="primary" @click="showVariableDialog = false">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import TableTemplate from "@/components/TableTemplate";
import {getListHistoryProcess, getListByTypeAndId} from "./api";

export default {
    name: "RunHistory",
    components: {
        TableTemplate
    },
    data() {
        return {
            responseData: {},
            searchParams: {
                studentName: "",
                bussinesskey: "",
                dorm: "",
                pageSize: 10,
                pageNum: 1
            },
            showHistoryDialog: false,
            showVariableDialog: false,
            historyList: [],
            variablesList: [],
            loading: false
        };
    },
    mounted() {
        this.getListHistoryProcessByParamsAndRender(this.searchParams);
    },
    methods: {
        getNodeStatusClass(row) {
            if (row.ended && row.endTime) return 'ended';
            switch (row.currentTask) {
                case '销假': return 'leave';
                case '辅导员审批': return 'approval';
                case '提交申请': return 'submit';
                default: return 'default';
            }
        },
        getNodeIcon(row) {
            if (row.ended && row.endTime) return 'el-icon-check';
            switch (row.currentTask) {
                case '销假': return 'el-icon-time';
                case '辅导员审批': return 'el-icon-edit-outline';
                case '提交申请': return 'el-icon-document-add';
                default: return 'el-icon-loading';
            }
        },
        getNodeText(row) {
            return row.ended && row.endTime ? '流程结束' : row.currentTask;
        },
        getListHistoryProcessByParamsAndRender(params) {
            const {pageNum = 1, pageSize = 10, studentName = "", bussinesskey = "", dorm=""} = params;
            const roles = this.$store.getters.roles || [];
            
            this.loading = true;
            getListHistoryProcess({
                pageSize,
                pageNum,
                isAsc: "asc",
                name: "",  // 不再使用流程名称搜索
                bussinesskey,  // 业务号搜索
                startUserId: studentName,  // 使用startUserId作为姓名搜索
                dorm,  // 宿舍号（后端会处理）
                roles: roles,
                isDormManager: roles.includes('dormManager')
            }).then(res => {
                this.responseData = res;
            }).catch(error => {
                console.error('Search error:', error);
                this.$message.error('搜索失败，请重试');
            }).finally(() => {
                this.loading = false;
            });
        },
        search() {
            this.searchParams.pageNum = 1;
            this.getListHistoryProcessByParamsAndRender(this.searchParams);
        },
        reset() {
            this.searchParams = {
                studentName: "",
                bussinesskey: "",
                dorm: "",
                pageSize: 10,
                pageNum: 1
            };
            this.getListHistoryProcessByParamsAndRender(this.searchParams);
        },
        handleSizeChange(val) {
            this.searchParams.pageSize = val;
            this.getListHistoryProcessByParamsAndRender(this.searchParams);
        },
        handleCurrentChange(val) {
            this.searchParams.pageNum = val;
            this.getListHistoryProcessByParamsAndRender(this.searchParams);
        },
        showHistory(row) {
            this.showHistoryDialog = true;
            getListByTypeAndId("history", row.processInstanceId).then(res => {
                this.historyList = res.rows;
            });
        },
        showVariable(row) {
            this.showVariableDialog = true;
            getListByTypeAndId("variables", row.processInstanceId).then(res => {
                this.variablesList = res.rows;
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.app-container {
    height: calc(100vh - 84px);
    padding: 15px;
    background-color: #f5f7fa;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.search-container {
    background: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);
    margin-bottom: 15px;

    .el-row {
        margin-bottom: 0 !important;
    }

    .el-input {
        .el-input__inner {
            border-radius: 4px;
            &:hover {
                border-color: #409eff;
            }
        }
    }

    .el-button-group {
        .el-button {
            padding: 9px 15px;
            &:hover {
                opacity: 0.8;
            }
        }
    }
}

.table-container {
    flex: 1;
    background: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);
    display: flex;
    flex-direction: column;
    overflow: visible;  // 改为可见，允许内容扩展
}

.el-table {
    flex: 1;
    overflow: hidden;  // 保持表格内部滚动

    &::before {
        display: none;
    }

    .el-table__header-wrapper {
        th {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: 500;
            height: 45px;
        }
    }

    .el-table__body-wrapper {
        overflow-y: auto;  // 关键调整：强制显示滚动条
        max-height: calc(100vh - 320px);  // 根据实际页面高度计算（可调整320px为顶部搜索+分页+边距的总高度）
    }

    .el-table__row {
        td {
            padding: 8px 0;
        }

        &:hover {
            td {
                background-color: #f5f7fa;
            }
        }
    }
}

.pagination-container {
    padding: 15px 0 0;
    text-align: right;
}

.status-tag {
    display: inline-flex;
    align-items: center;
    padding: 0 8px;
    height: 28px;
    border-radius: 4px;
    font-size: 13px;
    
    i {
        margin-right: 4px;
    }

    &.ended {
        background-color: #f0f9eb;
        color: #67c23a;
        border: 1px solid #c2e7b0;
    }

    &.leave {
        background-color: #fdf6ec;
        color: #e6a23c;
        border: 1px solid #f5dab1;
    }

    &.approval {
        background-color: #ecf5ff;
        color: #409eff;
        border: 1px solid #b3d8ff;
    }

    &.submit {
        background-color: #f4f4f5;
        color: #909399;
        border: 1px solid #d3d4d6;
    }
}

.time-display {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #606266;
    
    i {
        color: #909399;
    }
}

.el-tag {
    margin: 0 2px;
    
    &.el-tag--plain {
        background: transparent;
    }
}

// 新增班级标签样式
.class-tag {
    display: inline-flex;
    align-items: center;
    padding: 4px 8px;  // 增加内边距
    border-radius: 6px;  // 更圆润的圆角
    background-color: #f0f9eb;  // 浅绿色背景（可根据主题调整）
    border: 1px solid #e1f3d8;  // 浅边框
    color: #67c23a;  // 字体颜色
    
    i {
        margin-right: 6px;  // 图标与文字间距
    }
    
    // 鼠标悬停时轻微放大
    &:hover {
        transform: scale(1.02);
        transition: transform 0.1s ease;
    }
}
.ellipsis-text {
    display: inline-block;
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

// 新增操作按钮样式
.mini-btn {
    padding: 4px 8px;
    font-size: 12px;
    height: 24px;
}
</style>
